import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList: []
  },
  mutations: { //mutations中的每个方法尽可能完成的事情比较单一一点
    // addCart(state, payload) {
    //   let oldProduct = null
    //   state.cartList.forEach((item) => {
    //     if (item.iid === payload.iid) {
    //       oldProduct = item
    //     }
    //   })

    //   // let oldProduct = state.cartList.find(item => item.iid === payload.iid)

    //   if (oldProduct) {
    //     oldProduct.count += 1
    //   } else {
    //     payload.count = 1
    //     state.cartList.push(payload)
    //   }
    // }
    addCounter(state, payload) {
      payload.count++
    },
    addToCart(state, payload) {
      payload.checked = true
      state.cartList.push(payload)
    },
    changeChecked(state, payload) {
      state.cartList.forEach(item => {
        item.checked = payload
      })
    }
  },
  actions: {
    addCart(context, payload) {
      return new Promise((resolve, reject) => {
        let oldPrice = context.state.cartList.find(item => item.iid === payload.iid)
        if (oldPrice) {
          context.commit('addCounter', oldPrice)
          resolve('当前的商品数量+1')
        } else {
          payload.count = 1
          context.commit('addToCart', payload)
          resolve('成功加入购物车')
        }
      })
    }
  },
  getters: {
    cartLength(state) {
      return state.cartList.length
    },
    cartList(state) {
      return state.cartList
    }
  },
  modules: {}
})
